package cn.hxzy.user.dao;

import cn.hxzy.user.entity.Resource;
import cn.hxzy.user.util.DBUtil;
import cn.hxzy.user.util.DataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class ResourceDao extends BaseDao<Resource> {

    public List<Resource> findAll() throws Exception {
        Connection connection = DataSource.getConnection();
        List<Resource> select = DBUtil.select(connection, "order by order_number", null, Resource.class);
        DataSource.closeConnection(connection);
        return select;
    }

    public List<Resource> findByPid(int i) throws Exception {
        Connection connection = DataSource.getConnection();
        List<Resource> select = DBUtil.select(connection, "where pid = ? order by order_number", new Object[]{i}, Resource.class);
        DataSource.closeConnection(connection);
        return select;
    }

    public List<Resource> findByRoleIdNotHave(int id) throws Exception {
        Connection connection = DataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement("SELECT * FROM `resource` WHERE id NOT IN(SELECT r.id FROM `resource` r LEFT JOIN `role_resource` rr ON  rr.`resource_id`=r.id WHERE rr.`role_id` = ?) order by order_number");
        statement.setObject(1, id);
        ResultSet resultSet = statement.executeQuery();
        List<Resource> list = new ArrayList<>();
        while (resultSet.next()) {
            Resource resource = new Resource(resultSet.getString("name"), resultSet.getString("url"), resultSet.getInt("pid"),resultSet.getInt("order_number"));
            resource.setId(resultSet.getInt("id"));
            resource.setCreateTime(resultSet.getTimestamp("create_time"));
            resource.setUpdateTime(resultSet.getTimestamp("update_time"));
            list.add(resource);
        }
        resultSet.close();
        statement.close();
        DataSource.closeConnection(connection);
        return list;
    }
}
